<template>
	<div  class="wrapper">
		<div  style="position: relative;">
		<i class="el-icon-close" @click="closeDialogTop()" style="position:absolute;cursor: pointer; font-size:22px; top: -48px; right: 0px"></i>
    </div>
<!--    经销商基础信息维护-->
				<BreakSpace :label="labels[0].title" :containerStyle="{ marginBottom: '10px' }" />
				<infoBase ref="infoBase" :formType="value.type" :formOptions="value" v-model="formData" @formchange="infoBaseChange"/>
<!--    区域信息-->
        <BreakSpace :label="labels[1].title" :containerStyle="{ marginBottom: '10px' }" />
        <infoArea ref="infoArea" :formType="value.type" :formOptions="value" v-model="formData" @formchange="infoAreaChange"/>
<!--    注册信息-->
        <BreakSpace :label="labels[2].title" :containerStyle="{ marginBottom: '10px' }" />
        <infoPower ref="infoPower" :formType="value.type" :formOptions="value" v-model="formData" @formchange="infoPowerChange"/>
<!--    财务信息-->
        <BreakSpace :label="labels[3].title" :containerStyle="{ marginBottom: '10px' }" />
        <infoFinance ref="infoFinance" :formType="value.type" :formOptions="value" v-model="formData" @formchange="infoFinanceChange"/>
<!--    物流信息-->
        <BreakSpace :label="labels[4].title" :containerStyle="{ marginBottom: '10px' }" />
        <infoLogistics ref="infoLogistics" :formType="value.type" :formOptions="value" v-model="formData" @formchange="infoLogisticsChange"/>
<!--    关键岗位信息-->
<!--        <BreakSpace :label="labels[5].title" :containerStyle="{ marginBottom: '10px' }" />-->
<!--        <infoStation ref="infoStation" :formType="value.type" :formOptions="value" v-model="formData" @formchange="infoStationChange"/>-->
<!--    授权车型-->
        <BreakSpace :label="labels[5].title" :containerStyle="{ marginBottom: '10px' }" />
        <infoProduct ref="infoProduct" :formType="value.type" :formOptions="value" v-model="formData" @formchange="infoProductChange"/>
<!--    授权地域-->
        <BreakSpace :label="labels[6].title" :containerStyle="{ marginBottom: '10px' }" />
        <infoZone ref="infoZone" :formType="value.type" :formOptions="value" v-model="formData" @formchange="infoZoneChange"/>

        <!--<BreakSpace :label="labels[4].title" :containerStyle="{ marginBottom: '10px' }" />-->
				<!--<infoCompany ref="infoCompany" :formType="value.type" :formOptions="value" v-model="formData" @formchange="infoCompanyChange"/>-->

        <!--<BreakSpace :label="labels[5].title" :containerStyle="{ marginBottom: '10px' }" />-->
				<!--<infoStock ref="infoStock" :formType="value.type" :formOptions="value" v-model="formData" @formchange="infoStockChange"/>-->
		<div class="dialogBottmView">
			<el-button @click="closeDialogTop">关 闭</el-button>
			<el-button @click="determineDialog()"  v-if="value.type!=='show'" type="primary">保 存</el-button>
			<!-- <el-button @click="determineDialog()" v-if="value.type!=='show'" :disabled="this.formData.status === this.types.DEALER_INFO_STATUS_ENABLE" type="primary">确 定</el-button> -->
<!--			<el-button @click="determineDialog()" v-if="value.type!=='show'" :disabled="okDisabled" type="primary">确 定</el-button>-->
		</div>
	</div>
</template>

<script>
	import { authority } from '@/utils/authMixin';
	import { dictionary } from '@/utils/dictMixin';

	import autoLoding from '@/utils/loding';//等待框
	import infoBase from '../dealerForm/infoBase'; //经销商基础信息维护
  import infoArea from '../dealerForm/infoArea';//区域信息
	import infoProduct from '../dealerForm/infoProduct';//授权车型
	import infoPower from '../dealerForm/infoPower'; //注册信息
  import infoFinance from '../dealerForm/infoFinance'; //财务信息
	import infoCompany from '../dealerForm/infoCompany';
	import infoStock from '../dealerForm/infoStock';
	import infoLogistics from '../dealerForm/infoLogistics';//物流信息
  import infoStation from '../dealerForm/infoStation';//关键岗位信息
  import infoZone from '../dealerForm/infoZone';//授权地域
	// import infoOpinion from '../dealerForm/infoOpinion'; //审核信息

	import { getDetails } from '@/api/cms-api/origin/originInfo';
	import { addAllData, editAllData, addDetermine, editDetermine } from '@/api/cms-api/origin/originInfo/OEM';
	import * as types from '@/api/cms-api/origin/originInfo/types';
	import { dealerCommon } from '@/api/cms-api/origin/commonDealerType';		//经销商类型工具类
	import { isArray } from 'util';
  import {parseTime } from '@/utils/index';

	import vm from './bridge';

	export default {
		mixins: [authority, dictionary, autoLoding,dealerCommon],
		components: {
			infoBase,infoArea,infoProduct,infoPower,infoCompany,infoStock,infoFinance,infoLogistics,infoZone,infoStation
		},
		props:{
			value: {
				type: Object,
				required: true
			},
		},
		data() {
			return {
				okDisabled:false,
				formData:{},
				labels: [
					{ title: '经销商基础信息维护', id: 'row-01' },
					{ title: '区域信息', id: 'row-02' },
					{ title: '注册信息', id: 'row-03' },
					{ title: '财务信息', id: 'row-04' },
					{ title: '物流信息', id: 'row-05' },
          // { title: '关键岗位信息', id: 'row-06' },
					{ title: '授权车型', id: 'row-06' },
          { title: '授权地域', id: 'row-07' }
				],
				loadingVm:null,
				types:types
			};
		},
		mounted(){
      try{
        if(this.value.type != 'add'){
          // this.loadingVm = this.openLoding('.cover-container');
          //按ID获取数据
          this.init();
        }
      }finally{
        // this.closeLoding(this.loadingVm);
      }
		},
		methods: {
			async init(){
			  try{
          let res = await getDetails(this.value.id,{});
          if(res.resultCode === 200){
            //转换附件为list<Sting>
            this.formData = this.transformAllEnclosureString(res.data);
            this.formData.inputNumber = '';
            this.formData.inputChar = '';
            this.$nextTick(() =>{
              this.$refs.infoBase.init();
              this.$refs.infoArea.init();
              this.$refs.infoPower.init();
              this.$refs.infoFinance.init();
              this.$refs.infoLogistics.init();
              this.$refs.infoProduct.init();
              this.$refs.infoZone.init();
            });
          }
        }catch(e){
          console.log("页面初始化异常:", e);
        }

			},

			//打开等待遮罩
			openLoding(options){
				let defOptions = {	// 声明一个loading对象
					lock: true, // 是否锁屏
					fullscreen: false,
					body: false,
					target: '.mainAnchor', // 需要遮罩的区域
				};
				defOptions = Object.assign(defOptions,options);
				// this.loadingVm = this.$loading(defOptions);
				return this.$loading(defOptions);
			},
			//关闭等待遮罩
			closeLoding(loading){
				loading.close();
			},

      //保存（不验证）
      async saveDialog(){
			  try{
          this.loadingVm = this.openLoding('.cover-container');
          let allData = this.getSavingData();
          allData.auditStatus = types.DEALER_INFO_STATUS_SAVED;

          if(allData.dealerCompanyId == null || allData.dealerCompanyId == ""){
            if(this.value.type == 'add'){
              this.$notify.warning({title: '提示信息',message:'必须手动选择一个经销商公司'});
              return;
            }
          }
          await this.save(allData);
        }finally {
          this.closeLoding(this.loadingVm);
        }

      },

			//确定（验证并提交）
			async determineDialog() {
			  try{
          this.loadingVm = this.openLoding('.cover-container');
          let allData = this.getSavingData();
          allData.auditStatus = types.DEALER_INFO_STATUS_SAVED;
          // allData.auditStatus = types.DEALER_INFO_STATUS_TO_BE_SUBMITTED;

          if(allData.dealerCompanyId == null || allData.dealerCompanyId == ""){
            if(this.value.type == 'add'){
              this.$notify.warning({title: '提示信息',message:'必须手动选择一个经销商公司'});
              return;
            }
          }
          if(allData.logisticsList.length == 0){
            this.$notify.warning({title: '提示信息',message:'至少添加一条地址信息'});
            return;

          }
          let f1 = await this.$refs.infoBase.saveDialog();
          let f2 = await this.$refs.infoLogistics.saveDialog();
          let f3 = await this.$refs.infoProduct.saveDialog();
          let f4 = await this.$refs.infoPower.saveDialog();
          let f5 = await this.$refs.infoFinance.saveDialog();
          let f6 = await this.$refs.infoArea.saveDialog();
          if(!f1 || !f2 || !f3 || !f4 || !f5 || !f6){
            console.log("validate result:",f1,f2,f3,f4,f5,f6);
            return;
          }
          await this.save(allData);
          // await this.saveDetermine(allData);
        }finally {
          this.closeLoding(this.loadingVm);
        }

			},

      /**
       * 获取待提交数据
       * @returns {*|{}}
       */
      getSavingData(){
        //取数据
        let allData = { ... this.formData};
        allData.shopBusinessType = types.SHOP_BUSINESS_SALES;

        //基本信息
        this.$refs.infoBase.$refs.FormPanel.excuteFormData(this.$refs.infoBase.$refs.FormPanel.form);
        allData = Object.assign(allData,this.$refs.infoBase.$refs.FormPanel.form);
        allData = Object.assign(allData,this.$refs.infoBase.$data.hiddenFormData);


        //区域信息
        this.$refs.infoArea.$refs.FormPanel.excuteFormData(this.$refs.infoArea.$refs.FormPanel.form);
        let salesAreaInfo = Object.assign({},this.formData.salesAreaInfo);
        salesAreaInfo = Object.assign(salesAreaInfo, this.$refs.infoArea.$refs.FormPanel.form);
        salesAreaInfo = Object.assign(salesAreaInfo,this.$refs.infoArea.$data.hiddenFormData);
        allData.salesAreaInfo = salesAreaInfo;

        //注册信息
        this.$refs.infoPower.$refs.FormPanel.excuteFormData(this.$refs.infoPower.$refs.FormPanel.form);
        allData = Object.assign(allData,this.$refs.infoPower.$refs.FormPanel.form);


        //财务信息
        this.$refs.infoFinance.$refs.FormPanel.excuteFormData(this.$refs.infoFinance.$refs.FormPanel.form);
        allData = Object.assign(allData,this.$refs.infoFinance.$refs.FormPanel.form);

        //物流信息
        allData.logisticsList = this.$refs.infoLogistics.saveData.xxList;
        allData.insertLogisticsList = this.$refs.infoLogistics.$refs.tableInfo.GET_INSERT_ROWS();
        allData.updateLogisticsList = this.$refs.infoLogistics.$refs.tableInfo.GET_UPDATE_ROWS();
        allData.deleteLogisticsList = this.$refs.infoLogistics.$refs.tableInfo.GET_DELETE_ROWS();

        //授权车型
        this.$refs.infoProduct.$refs.FormPanel.excuteFormData(this.$refs.infoProduct.$refs.FormPanel.form);
        allData = Object.assign(allData,this.$refs.infoProduct.$refs.FormPanel.form);

        //授权地域
        allData.zoneList = this.$refs.infoZone.saveData.xxList;
        allData.deleteZoneList = this.$refs.infoZone.$refs.tableInfo.GET_DELETE_ROWS();

        //时间转换
        allData.joinTime = this.transTiming(allData.joinTime);
        allData.offlineDate = this.transTiming(allData.offlineDate);
        allData.establishmentDate = this.transTiming(allData.establishmentDate);
        return allData;
      },

      transTiming(value){
        console.log("timing orgin value:",value);
        let regex = /^[1-2][0-9][0-9][0-9]-([1][0-2]|0?[1-9])-([12][0-9]|3[01]|0?[1-9])$/;
        let regex2 = /^[1-2][0-9][0-9][0-9]-([1][0-2]|0?[1-9])-([12][0-9]|3[01]|0?[1-9]) ([01]?[0-9]|[2][0-3]):([0-5][0-9]):([0-5][0-9])$/;
        if (regex.test(value)) {
          value = value + " 00:00:00";
        }else if(regex2.test(value)){
          value = value;
        }else{
          value = value;
        }
        return value;
      },


			//取消操作
			closeDialogTop() {
				this.$confirm('确认关闭窗口吗？您所做的操作将不会被保存！', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(() => {
					this.$emit('close', { visible: false });
				})
			},
			infoBaseChange(data){
				// console.log(2)
				this.$refs.infoBase.saveDialog();
			},
      infoAreaChange(data){
        // console.log(3)
        this.$refs.infoArea.saveDialog();
      },
			infoProductChange(data){
				// console.log(3)
				this.$refs.infoProduct.saveDialog();
			},
			infoPowerChange(data){
				// console.log(4)
				this.$refs.infoPower.saveDialog();
			},
			infoCompanyChange(data){
				// console.log(5)
				this.$refs.infoCompany.saveDialog();
			},
			infoStockChange(data){
				// console.log(5)
				this.$refs.infoStock.saveDialog();
			},
      infoFinanceChange(_data){
        // console.log(5)
       this.$refs.infoFinance.saveDialog();
      },
      infoStationChange(_data){
        // console.log(5)
        this.$refs.infoStation.saveDialog();
      },

      infoLogisticsChange(data){
			  this.$refs.infoLogisticsChange.saveDialog();
      },
      infoZoneChange(data){
			  this.$refs.infoZone.saveDialog();
      },
			//判断当前是否需要生成经销商代码
			generateAsNeeded(){
				//不存在经销商代码
				return !this.formData.dealerCode;
			},


			//转化表单的附件 转换为list<Map<String,Object>>（提交前使用）
			//不再使用由IMG转FILE
			transformAllEnclosure(data){
				let rdata = Object.assign({},data);

				rdata.designFeeEnclosureList = this.transformEnclosureList(rdata.designFeeEnclosureList);	//设计费附件
				rdata.cashDepositEnclosureList = this.transformEnclosureList(rdata.cashDepositEnclosureList);	//保证金附件

				rdata.businessLicenseEnclosureList = this.transformEnclosureList(rdata.businessLicenseEnclosureList);	//营业执照扫描件
				rdata.legalRepresentativeEnclosureList = this.transformEnclosureList(rdata.legalRepresentativeEnclosureList);	//法定代表人附件
				rdata.firstPaymentEnclosureList = this.transformEnclosureList(rdata.firstPaymentEnclosureList);	//首笔提车款附件

				rdata.openAccountProveEnclosureList = this.transformEnclosureList(rdata.openAccountProveEnclosureList);	//开户证明附件

				rdata.licenceEnclosureList = this.transformEnclosureList(rdata.licenceEnclosureList);	//许可证附件
				return rdata;
			},
			//转化表单的附件 转换为list<Sting>（回显使用）
			transformAllEnclosureString(data){
				let rdata = data;

				rdata.designFeeEnclosureList = this.transformEnclosureStringList(rdata.designFeeEnclosureList);	//设计费附件
				rdata.cashDepositEnclosureList = this.transformEnclosureStringList(rdata.cashDepositEnclosureList);	//保证金附件

				rdata.businessLicenseEnclosureList = this.transformEnclosureStringList(rdata.businessLicenseEnclosureList);	//营业执照扫描件
				rdata.legalRepresentativeEnclosureList = this.transformEnclosureStringList(rdata.legalRepresentativeEnclosureList);	//法定代表人附件
				rdata.firstPaymentEnclosureList = this.transformEnclosureStringList(rdata.firstPaymentEnclosureList);	//首笔提车款附件

				rdata.openAccountProveEnclosureList = this.transformEnclosureStringList(rdata.openAccountProveEnclosureList);	//开户证明附件

				rdata.licenceEnclosureList = this.transformEnclosureStringList(rdata.licenceEnclosureList);	//许可证附件

				//经销商形式
				let dealerAttachAuthList = [];
				if(isArray(rdata.dealerAttachAuthList)){
					rdata.dealerAttachAuthList.forEach(x => {
						dealerAttachAuthList.push(x.financeCompanyId);
					});
				}
				rdata.dealerAttachAuthList = dealerAttachAuthList;

				//车系
				let dealerAttachSeriesList = [];
				if(isArray(rdata.dealerAttachSeriesList)){
					rdata.dealerAttachSeriesList.forEach(x => {
						dealerAttachSeriesList.push(x.seriesId);
					});
				}
				rdata.dealerAttachSeriesList = dealerAttachSeriesList;

				//车型
				let dealerAttachModelList = [];
				if(isArray(rdata.dealerAttachModelList)){
					rdata.dealerAttachModelList.forEach(x => {
						dealerAttachModelList.push(x.modelId);
					});
				}
				rdata.dealerAttachModelList = dealerAttachModelList;
				return rdata;
			},
			//转换成附件对象 转换为list<Map<String,Object>>
			transformEnclosureList(list){
				let fileUrlList = [];
				if(!isArray(list)){
					return fileUrlList;
				}
				//不再使用由IMG转FILE
				// for (let i = 0; i < list.length; i++) {
				// 	let fileUrl = list[i];
				// 	fileUrl = fileUrl.replace(/\\/g,"/");
				// 	fileUrlList.push(Object.assign({},{"name":fileUrl.substring(fileUrl.lastIndexOf('/')+1)},{"url":fileUrl}));
				// }
				// return fileUrlList;
				return list;
			},
			//转换成附件对象(回显) 转换为list<Sting>
			transformEnclosureStringList(list){
				let fileUrlList = [];
				if(!isArray(list)){
					return fileUrlList;
				}
				//不再使用由IMG转FILE
				// for (let i = 0; i < list.length; i++) {
				// 	let fileUrl = list[i];
				// 	fileUrlList.push(fileUrl.fileId);
				// }
				list.forEach(x => {
					fileUrlList.push({name:x.fileName,url:x.fileId});
				});
				return fileUrlList;
			},

			async save(data){
				//保存主表数据
				let res = {};
				if(this.value.type === 'add'){
					res = await addAllData(data);
				}else{
					res = await editAllData(this.value.id,data);
				}
				if(res.resultCode === 200) {
					this.$notify.success({title: '提示信息',message:'保存成功!'});
					this.$emit('close','refresh');
				}else {
					this.$notify.error({title: '提示信息',message:res.errMsg||'保存失败!'});
				}
			},
			async saveDetermine(data){
				let res = {};
				// console.log("data =>",data);
				// this.closeLoding(this.loadingVm);
				// return;
				if(this.value.type === 'add'){
					res = await addDetermine(data);
				}else{
					res = await editDetermine(this.value.id,data);
				}
				if(res.resultCode === 200) {
					this.$notify.success({title: '提示信息',message:'确认成功!'});
					this.$emit('close','refresh');
				}else {
					this.$notify.error({title: '提示信息',message:res.errMsg||'确认失败!'});
				}
			},
		},
	};
</script>

<style scoped>
	.wrapper,.line {
		height: calc(100vh - 135px);
	}
	.line{
		overflow-x:hidden;
		overflow-y:auto;
	}
</style>
